<?php
/*****************************************************************
 * Fusion.Board
 *
 * @author                Denis Wrobel
 * @license               http://www.gnu.org/licenses/gpl-3.0.html
 * @version               0.1
 *
 *****************************************************************/

if( !defined( 'IN_SCRIPT' ) )
{
    die( 'Go Away!' );
}


class User
{
    private $user_id = -1;
    private $session_id = '';
    public $user_ip = '';
    public $user_agent = '';
    
    public function __construct()
    {
        $this->session_id = session_id();
        $this->user_ip = substr( $_SERVER['REMOTE_ADDR'], 0, 16 );
        $this->user_agent = addslashes( substr( $_SERVER['HTTP_USER_AGENT'], 0, 255 ) );
    }
    
    
    /*
     * Init session sysem
     */
    public function initialize()
    {
        global $db;
        
        //Search for session in DB
        $query = $db->query( 'SELECT s.*, u.*, a.*
                              FROM ' . TABLE_PREFIX . 'sessions s
                              LEFT JOIN ' . TABLE_PREFIX . 'users u
                              ON u.user_id = s.session_user
                              LEFT JOIN ' . TABLE_PREFIX . 'groups_acl a
                              ON a.parent_group = u.user_maingroup
                              WHERE s.session_id = \''. $this->session_id .'\'' );
        
        $session_data = $db->fetch( $query );
        
        if( !strlen( $session_data['session_user'] ) )
        {
            $session_data['session_user'] = '0';
        }
        
        $location = $db->escape( $_SERVER['PHP_SELF'] ); //User localization
        if( count( $_GET ) )
        {
            $runs = 0; //Loop runs
            foreach( $_GET AS $get_name => $get_value )
            {
                if( $runs == 0 )
                {
                    $location .= '?' . $db->escape( $get_name ) . '=' . $db->escape( $get_value );
                }
                else
                {
                    $location .= '&' . $db->escape( $get_name ) . '=' . $db->escape( $get_value );
                }
                
                $runs++;
            }
        }
        
        if( !$session_data['session_id'] )
        {
            //Session not found, create new
            $db->query( 'INSERT INTO ' . TABLE_PREFIX . 'sessions( session_id, session_user, session_ip, session_location, session_starttime, session_lasttime, session_logged )
                         VALUES( \'' . $this->session_id .  '\', 0, \'' . $this->user_ip . '\', \'' . $location . '\', \'' . time() . '\', \'' . time() . '\', 0 )' );
            
            $this->user_id = 1;
            
            $this->initialize();
        }
        else
        {
            //Session found
            $db->query( 'UPDATE ' . TABLE_PREFIX . 'sessions
                         SET session_lasttime = \'' . time() . '\',
                         session_location = \'' . $location . '\'
                         WHERE session_id = \'' . $this->session_id . '\'' );
        }
        
        return $session_data;
    }
    
    /*
     * Add new user
     * @param string $username Username
     * @param string $password Password
     * @param string $email Email
     * @param string $acrivate_key Key to activate account
     */
    public function addUser( $username, $password, $email, $activate_key )
    {
        global $db;
        
        $passkey = '';
        
        $alphabet = range( 'a', 'z' );
        $numbers = range( 0, 9 );
        for( $i = 0; $i <= 5; $i++ )
        {
            $rand = rand( 0, 5 );
            if( $rand >= 4 )
            {
                $passkey .= $numbers[ rand( 0, 9 ) ];
            }
            else
            {
                if( rand( 0, 1 ) == 1 )
                {
                    $passkey .= ucfirst( $alphabet[ rand( 0, 23 ) ] );
                }
                else
                {
                    $passkey .= $alphabet[ rand( 0, 23 ) ];
                }
            }
        }
        
        $is_active = ( $board['account_activation'] ) ? 0 : 1;
        
        $adduser = $db->query( 'INSERT INTO ' . TABLE_PREFIX . 'users ( user_id, username, user_password, user_passkey, user_email, account_active, activate_key, join_date )
                                VALUES ( null, \'' . $username . '\', \'' . md5( $passkey . $password ) . '\', \'' . $passkey . '\', \'' . $email . '\', \'' . $is_active . '\', \'' . $activate_key . '\', \'' . time() . '\' )' );
    
        if( $adduser )
        {
            $db->query( 'UPDATE ' . TABLE_PREFIX . 'stats
                         SET users = (users + 1)' );
            
            $query = $db->query( 'SELECT MAX(user_id) AS user_id
                                  FROM ' . TABLE_PREFIX . 'users' );
            
            $last = $db->fetch( $query );
            
            return $last['user_id'];
        }
        else
        {
            return false;
        }
    }
    
   /*
     * User log in
     * @param string $username Username
     * @param string $password Password
     * @param integer $remember Remember user
     * @param integer $as_hidden Hide?
     */
    public function logIn( $username, $password, $remember = 1, $as_hidden = 0 )
    {
        global $db, $board, $core;
        
        $sid = $this->session_id;
        
        $query = $db->query( 'SELECT user_id, username, user_password, user_passkey, account_active
                              FROM ' . TABLE_PREFIX . 'users
                              WHERE username = \'' . $username . '\'' );
        $result = $db->fetch( $query );
        
        if( $result['account_active'] == 0 && $board['account_activation'] )
        {
            //Account not activated
            return 2;
        }
        elseif( $result['account_active'] && $result['user_id'] )
        {
            if( md5( $result['user_passkey'] . $password ) != $result['user_password'] )
            {
                //Invalid login data
                return 0;
            }
            else
            {
                //All ok
                if( $remember == 1 )
                {
                    $al_key = md5( microtime() );
                    
                    $db->query( 'UPDATE ' . TABLE_PREFIX . 'sessions
                                 SET autologin_key = \'' . $al_key . '\'
                                 WHERE session_id = \'' . $sid . '\'' );
                }
                
                $db->query( 'UPDATE ' . TABLE_PREFIX . 'sessions
                             SET session_user = ' . $result['user_id'] . ',
                             session_logged = 1
                             WHERE session_id = \'' . $sid . '\'');
                $db->query( 'UPDATE ' . TABLE_PREFIX . 'users
                             SET last_login = \'' . time() . '\'
                             WHERE user_id = ' . $result['user_id'] );
                
                if( $remember == 1 )
                {
                    $cookieData = '{a:1;s:' . $sid . ';u:' . $result['user_id'] . ';k:' . $al_key . ';}';
                    $core->createCookie( 'data', $cookieData, 1209600 ); //Autologin for 14 days
                }
                
                return 1;
            }
        }
        else
        {
            return 0;
        }
    }
    
    /*
     * Return userdata
     * @param integer $user_id User id
     */
    public function userdata( $user_id = 0 )
    {
        global $db;
        
        $query = $db->query( 'SELECT u.*, g.*, r.*
                              FROM ' . TABLE_PREFIX . 'users u
                              LEFT JOIN ' . TABLE_PREFIX . 'groups g
                              ON g.group_id = u.user_maingroup
                              LEFT JOIN ' . TABLE_PREFIX . 'ranks r
                              ON r.rank_minposts >= u.user_posts
                              AND r.rank_minposts < ( u.user_posts + 1 )
                              WHERE u.user_id = \'' . $user_id . '\'
                              AND u.user_id > 1' );
        
        return $db->fetch( $query );
    }
    
    /*
     * Return 1 if user is online
     * @param integer $user_id User id
     */
    public function userStatus( $user_id )
    {
        global $db, $board;
        
        $query = $db->query( 'SELECT *
                              FROM ' . TABLE_PREFIX . 'sessions
                              WHERE session_user = ' . $user_id . '
                              ORDER BY session_lasttime DESC LIMIT 1' );
        
        $result = $db->fetch( $query );
        
        if( $result['session_lasttime'] > ( time() - ( $board['stat_time'] * 60 ) ) )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    /*
     * Get profiles comments
     * @param string $profile_id Profile ID
     */
    public function getComments( $profile_id = 0, $start = 0, $perPage = 12 )
    {
        global $db;
        
        $query = $db->query( 'SELECT c.*, u.user_id, u.username
                              FROM ' . TABLE_PREFIX . 'comments c
                              LEFT JOIN ' . TABLE_PREFIX . 'users u
                              ON u.user_id = c.comment_author
                              WHERE c.comment_profile = \'' . $profile_id . '\'
                              ORDER BY c.comment_date DESC
                              LIMIT ' . $start . ',' . $perPage );
        
        $comments = array();
        
        while( $row = $db->fetch( $query ) )
        {
            $comments[] = $row;
        }
        
        return $comments;
    }
    
    /*
     * Add comment
     * @param integer $profile_id
     * @param integer $author comment author
     * @param string $message Comment text
     */
    public function addComment( $profile_id, $author_id, $message )
    {
        global $db;
        
        $insert = $db->query( 'INSERT INTO ' . TABLE_PREFIX . 'comments ( comment_id, comment_profile, comment_author, comment_message, comment_date )
                               VALUES ( null, \'' . $profile_id . '\', \'' . $author_id . '\', \'' . $message . '\', \'' . time() . '\' )' );
    
        if( $insert )
        {
            $updateStats =  $db->query( 'UPDATE ' . TABLE_PREFIX . 'users
                                         SET profile_comments = ( profile_comments + 1 )
                                         WHERE user_id = \'' . $profile_id . '\'' );
            
            return $updateStats;
        }
        else
        {
            return false;
        }
    }

    /*
     * Return comment data
     * @param integer $comment_id
     */
    public function commentData( $comment_id )
    {
        global $db;
        
        $query = $db->query( 'SELECT *
                              FROM ' . TABLE_PREFIX . 'comments
                              WHERE comment_id = \'' . $comment_id . '\'' );
        
        return $db->fetch( $query );
    }
    
    /*
     * Delete comment
     * @param integer $comment_id
     */
    public function deleteComment( $comment_id )
    {
        global $db;
        
        $updateStats =  $db->query( 'UPDATE ' . TABLE_PREFIX . 'users
                                     SET profile_comments = ( profile_comments - 1 )
                                     WHERE user_id = ( SELECT comment_profile FROM ' . TABLE_PREFIX . 'comments WHERE comment_id = \'' . $comment_id . '\' )' );
        
        if( $updateStats )
        {
            $removeComment = $db->query( 'DELETE FROM ' . TABLE_PREFIX . 'comments
                                          WHERE comment_id = \'' . $comment_id . '\'' );
            
            return $removeComment;
        }
        else
        {
            return false;
        }
    }
    
    /*
     * Logout user
     */
    public function logout()
    {
        global $db;
        
        return $db->query( 'UPDATE ' . TABLE_PREFIX . 'sessions
                            SET session_user = 1,
                            session_logged = 0
                            WHERE session_id = \'' . $this->session_id . '\'' );
    }
    
    /*
     * Check if person is on $user_id friends list
     * @param integer $buddy Buddy id
     * @param integer $user_id User id
     */
    public function searchFriend( $buddy, $user_id )
    {
        global $db;
        
        $query = $db->query( 'SELECT *
                              FROM ' . TABLE_PREFIX . 'friends
                              WHERE buddy_id = \'' . $buddy . '\'
                              AND parent_user = \'' . $user_id . '\'' );
        
        return $db->fetch( $query );
    }
    
    /*
     * Add new friend
     * @param integer $buddy Buddy id
     * @param integer $user_id User id
     */
    public function addFriend( $buddy, $user_id )
    {
        global $db;
        
        return $db->query( 'INSERT INTO ' . TABLE_PREFIX . 'friends( buddy_id, parent_user )
                            VALUES( \'' . $buddy . '\', \'' . $user_id . '\' )' );
    }
    
    /*
     * Get user friends
     * @param integer $user_id User id
     */
    public function getFriends( $user_id )
    {
        global $db;
        
        $query = $db->query( 'SELECT f.*, u.user_id, u.username, u.user_maingroup, g.group_id, g.group_style
                              FROM ' . TABLE_PREFIX . 'friends f
                              LEFT JOIN ' . TABLE_PREFIX . 'users u
                              ON u.user_id = f.buddy_id
                              LEFT JOIN ' . TABLE_PREFIX . 'groups g
                              ON g.group_id = u.user_maingroup
                              WHERE f.parent_user = \'' . $user_id . '\'' );
        
        $friends = array();
        
        while( $row = $db->fetch( $query ) )
        {
            $friends[] = $row;
        }
        
        return $friends;
    }
    
    /*
     * Remove friend
     * @param integer $buddy Buddy id
     * @param integer $user_id User id
     */
    public function removeFriend( $buddy, $user_id )
    {
        global $db;
        
        return $db->query( 'DELETE FROM ' . TABLE_PREFIX . 'friends
                            WHERE buddy_id = \'' . $buddy . '\'
                            AND parent_user = \'' . $user_id . '\'' );
    }
}
?>